package com.springcloud.sc.ucpv5.client.commondata.datachange;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.google.protobuf.Message;
import com.springcloud.sc.ucpv5.client.module.setting.SettingManager;
import com.springcloud.sc.ucpv5.client.util.CorbarUtil;

public class DataExChange {

    /**
     * 从当前通用对象获取probuf对象
     * 
     * @return
     */
    public Message dataChangeCommonToProBufData() {
	return DataExChangeUtil.dataChangeCommonToProBuf(this, true);
    }

    public org.omg.CORBA.portable.IDLEntity dataChangeCommonToCorbarData() {
	return DataExChangeUtil.dataChangeCommonToCorbar(this, true);
    }

    /**
     * 从probuf对象获取当前对象
     * 
     * @param builder_src
     * @return
     */
    public void dataChangeProBufDataToCommon(Message builder_src) {
	DataExChangeUtil.dataChangeProBufToCommon(this, builder_src, true);
    }

    /**
     * 从probuf对象获取当前对象
     * 
     * @param builder_src
     * @return
     */
    public void dataChangeCorbarDataToCommon(org.omg.CORBA.portable.IDLEntity builder_src) {
	DataExChangeUtil.dataChangeCorbaToCommon(this, builder_src, true);
    }

    /**
     * 从probuf流获取当前对象
     * 
     * @param data
     * @return
     */
    public void dataContentDataToCommon(byte[] data) {
	try {
	    if (SettingManager.SYS.ServerVerType_V5()) {
			// 获取probuf对象, 进行解压
		Message.Builder messageBuilder = DataExChangeUtil.dataChangeGetProBufBuilderClass(getClass().getName());
		Message message = null;
		// 运行pa
		try {
			Method m = messageBuilder.getClass().getMethod("mergeFrom", byte[].class);
			Message.Builder messageBuilder_ = (Message.Builder) m.invoke(messageBuilder, data);
			message = messageBuilder_.build();
		} catch (Exception e) {
			e.printStackTrace();
		}

		dataChangeProBufDataToCommon(message);
	    } else {
		// 获取corbar的holder对象
		org.omg.CORBA.portable.Streamable corbarHolder = DataExChangeUtil.dataChangeGetCorbaHolder(getClass().getName());
		CorbarUtil.byte2Struct(data, corbarHolder);

		Field[] field = corbarHolder.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
		// 第一个字段为value
		String name = field[0].getName(); // 获取属性的名字
		String type = field[0].getGenericType().toString(); // 获取属性的类型
		// 值
		Object field_value = field[0].get(corbarHolder);

		org.omg.CORBA.portable.IDLEntity entity = (org.omg.CORBA.portable.IDLEntity) field_value;

		// 将corba对象转换为通用对象
		if (entity != null) {
		    dataChangeCorbarDataToCommon(entity);
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * 获取cora对象的holder对象
     * 
     * @return
     */
    public org.omg.CORBA.portable.Streamable dataChangeCommonToCorbarDataHolder() {
	try {
	    org.omg.CORBA.portable.IDLEntity entity = dataChangeCommonToCorbarData();
	    org.omg.CORBA.portable.Streamable corbarHolder = DataExChangeUtil.dataChangeGetCorbaHolder(entity);
	    return corbarHolder;
	} catch (Exception e) {
	    e.printStackTrace();
	}

	return null;
    }

}
